<template>
    <section id="componentsContainer" v-loading="ideasLoading">
        <el-form ref="addFormRef" :model="addForm" inline status-icon>
            <el-form-item class="block">
                <h4>客户信息</h4>
            </el-form-item>
            <el-form-item label="客户类型:">
                <!-- <el-input v-model="customerDetail.companyPropertyName" disabled></el-input> -->
                <span>{{ customerDetail.companyPropertyName }}</span>
            </el-form-item>
            <el-form-item
                v-if="customerDetail.companyProperty === 'dic-company-property-001'"
                label="投放主体:"
                prop="city"
            >
                {{ customerDetail.company }}
                <!-- <el-input v-model="customerDetail.company" disabled></el-input> -->
            </el-form-item>
            <el-form-item label="品牌名称:" prop="planName">
                {{ customerDetail.brandName }}
                <!-- <el-input v-model="customerDetail.brandName" disabled></el-input> -->
            </el-form-item>
            <el-form-item label="客户行业:" prop="saleType">
                {{ customerDetail.industry }}
                <!-- <el-input v-model="customerDetail.industry" disabled></el-input>-->
            </el-form-item>

            <el-form-item
                v-if="customerDetail.companyProperty === 'dic-company-property-001'"
                label="签约主体:"
                prop="trade"
            >
                {{ customerDetail.signCompanyName }}
                <!-- <el-input v-model="customerDetail.signCompanyName" disabled></el-input> -->
            </el-form-item>
            <el-form-item
                v-if="customerDetail.companyProperty === 'dic-company-property-002'"
                label="签约人姓名:"
                prop="signUserName"
            >
                {{ customerDetail.signUserName }}
                <!-- <el-input v-model="customerDetail.signUserName" disabled></el-input> -->
            </el-form-item>
            <el-form-item class="block">
                <h4>方案信息</h4>
            </el-form-item>

            <el-form-item label="行业:" prop="deliveryMode">
                {{ ideasDetail.industryCodeName }}
            </el-form-item>
            <el-form-item label="媒体类型:" prop="seconds">
                {{ mediaType[planDetail.mediaType] }}
            </el-form-item>
            <el-form-item label="屏幕类型:" prop="numbers">
联动
</el-form-item>
            <el-form-item label="投放时长:" prop="time">
                {{ `${ideasDetail.time}` ? `${ideasDetail.time}秒` : '' }}
                <!-- <el-input v-model="ideasDetail.time" disabled>
                    <template #append> 秒 </template>
                </el-input> -->
            </el-form-item>
            <el-form-item class="block">
                <h4>关联创意</h4>
            </el-form-item>
            <el-form-item prop="endDate">
                <section class="ideas">
                    <el-select v-model="addForm.id" filterable placeholder="请选择">
                        <el-option v-for="item in ideasList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>

                    <el-tooltip placement="bottom" effect="light">
                        <template #content>
                            <div style="font-size: 14px; padding: 12px">
                                1.请确保创意的行业、媒体类型、时长、屏幕类型与方案一致；<br />
                                2.请确保创意的有效期大于等于方案投放结束时间；<br />
                                3.若为签约单客户，请确保创意的客户与方案签约单客户一致；<br />
                                若以上均满足仍无法查到创意，请联系运营人员！
                            </div>
                        </template>

                        <el-button type="text">
找不到创意？
</el-button>
                    </el-tooltip>
                </section>
            </el-form-item>
            <el-form-item class="block">
                <h4>素材规格</h4>
            </el-form-item>
        </el-form>

        <el-row v-if="planDetail.mediaType === 1" justify="start">
            <XcScreenType screen-type="inner" :top="screenModel.top" :bottom="screenModel.bottom" />
        </el-row>
        <el-row v-else-if="planDetail.mediaType === 2" :key="new Date().getTime()" type="flex" justify="start">
            <div class="out-screen">
                <XcScreenType
                    screen-type="out"
                    :top="screenModel.top"
                    :bottom="screenModel.bottom"
                    @on-play="onScreenPlay"
                    @get-instance="getOutScreenInstance"
                />
            </div>
            <div class="single-screen">
                <XcScreenType
                    screen-type="single"
                    :top="screenModelSingle.top"
                    :autoplay="false"
                    @on-play="onScreenPlay"
                />
            </div>
        </el-row>

        <el-dialog v-model="dialogVisible" title="提示" width="70%" :close-on-click-modal="false">
            <div class="mb-2">
关联创意失败，展示如下：
</div>
            <XcTable id="xc-table" :data="tableList" :columns="tableColumns" max-height="600px">
                <template #type="{ row }">
                    <span>{{ row.type === 'planPlay' ? '刊播计划' : '方案' }}</span>
                </template>
                <template #planPlayTime="{ row }">
                    <span :class="row.type === 'planPlay' ? 'red' : ''">{{ row.planPlayTime }}</span>
                </template>
                <template #planPlayAmount="{ row }">
                    <span :class="row.type === 'planPlay' ? 'red' : ''">{{ row.planPlayAmount }}</span>
                </template>
                <template #pointNumber="{ row }">
                    <span :class="row.type === 'planPlay' ? 'red' : ''">{{ row.pointNumber }}</span>
                </template>
            </XcTable>
            <el-alert
                class="mt-2 mb-2"
                title="须满足以上三个条件刊播计划 ≥ 确认投放状态的方案，才可提交！"
                type="warning"
                show-icon
                :closable="false"
            />
        </el-dialog>
    </section>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue';
// import XcScreenType from '@x-tech/fe-pc-components/src/components/XcScreenType/index.vue';

import XcScreenType from '@/views/delivery/creativeManage/components/XcScreenType.vue';

import _ from 'lodash';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
import { mediaType } from '@/utils/config';
import { getFormatDate, getProvinceAndCityFromRigions } from '@/utils/common.ts';
import { getPlanInfo, getCustomer, confirmIdeas } from '@/api/plan.ts';
import { planSreen2NormalSreen, customerType } from '@/utils/config';
import { searchCreativeList, getDetail } from '@/api/delivery/creativeManage';
import useTableSetting from '@/hooks/useTableSetting.ts';
import vidioNonSupport from '@/assets/screen_nonsupport.png';
import { ElMessageBox, ElMessage } from 'element-plus';
import { start } from 'repl';
import XcTable from '@x-tech/fe-pc-components/src/components/XcTableTemplate/XcTable.vue';

// 控制屏幕播放逻辑
let curPlayingScreen: any = null;
const onScreenPlay = (screenTypeIns: any) => {
    if (curPlayingScreen) {
        curPlayingScreen.setPauseState();
    }
    curPlayingScreen = screenTypeIns;
};
const getOutScreenInstance = (screenTypeIns: any) => {
    curPlayingScreen = screenTypeIns;
};

const route = useRoute();
const props = defineProps({
    isEdit: {
        type: Boolean,
        default: false,
    },
    isCreate: {
        type: Boolean,
        default: false,
    },
    planId: {
        type: Number,
        default: () => null,
    },
    ideasId: {
        type: Number,
        default: () => null,
    },
});
const { maxTableHeight, setTableMaxHeight } = useTableSetting({ id: 'componentsContainer', offsetBottom: 130 });

const store = useStore();
const planDetail = ref({});
const ideasList = ref([]);
const ideasLoading = ref(false);
const tableList = ref([]);
const tableColumns = [
    { label: '类型', key: 'type', render: true, prop: { minWidth: '220' } },
    { label: '总投放周期', key: 'planPlayTime', render: true, prop: { minWidth: '220' } },
    { label: '总金额（元）', key: 'planPlayAmount', render: true, prop: { minWidth: '150' } },
    { label: '刊位数', key: 'pointNumber', render: true, prop: { minWidth: '200' } },
];

const addForm = reactive({
    id: '',
});
const screenModel = reactive({
    top: {
        resourcesType: 2,
        src: '',
    },
    bottom: {
        leftSrc: null,
        rightSrc: null,
        src: '',
    },
});

const screenModelSingle = reactive({
    top: {
        resourcesType: 2,
        src: '',
    },
});

const ideasDetail = ref({
    industryCode: null,
    time: null,
    mediaType: 1,
});

const userInfo: any = computed(() => store.state.userGroup.userInfo);
const planId = computed(() => store.state.plan.planId);
const deleted = computed(() => store.state.plan.deleted);
const applyCode = route.query.applyCode || null;
const customerDetail = ref({
    companyProperty: null,
    company: null,
    brandName: null,
    industry: null,
    signCompanyName: null,
    signUserName: null,
});

const isCrm = computed(() => userInfo.value?.useCrm);
const groupCode = computed(() => userInfo.value?.groupCode);
const queryIdeas = async (name) => {
    const { endDate: planEndTime, screenType, trade, secondsName, mediaType } = planDetail.value;
    const params = {
        name,
        screenType: planSreen2NormalSreen[screenType],
        planEndTime,
        time: +secondsName.replace('s', ''),
        industryCode: trade,
        mediaType: planDetail.value.mediaType,
        // name,
        // screenType: 1,
        // planEndTime: '2022-10-28',
        // time: 15,
        // industryCode: 'HY002003',
    };
    if (isCrm.value) {
        params.customerId = customerDetail.value.customerId;
    }

    const data = await searchCreativeList(params) || [];

    ideasList.value = data.map((item) => ({
        ...item,
        label: `${item.brandName}-${item.applyCode}`,
    }));
};

const handleGetIdeaInfo = async (id) => {
    ideasLoading.value = true;
    const data = await getDetail(id) || {};

    ideasDetail.value = data;
    if (!isCrm.value) {
        const { brand, deliverySubject, id, industryCodeName, signName, type } = data.customerDTO || {};
        customerDetail.value = {
            ...customerType.value,
            company: deliverySubject,
            brandName: brand,
            companyPropertyName: type === 1 ? '企业' : '个人',
            companyProperty: type === 1 ? 'dic-company-property-001' : 'dic-company-property-002',
            industry: industryCodeName,
            signCompanyName: signName,
            signUserName: signName,
        };
    }

    console.log(' ideasDetail.value', ideasDetail.value);
    handleSreen(ideasDetail.value.materialDtoList);
    ideasLoading.value = false;
};

let curMediaType = 1;
const handleGetPlanInfo = async () => {
    ideasLoading.value = true;
    try {
        const isDel = props.isCreate ? false : deleted.value;
        const data = await getPlanInfo({ planId: planId.value, deleted: isDel }) || {};

        planDetail.value = data;
        console.log('++++', planDetail.value);

        ideasDetail.value.industryCodeName = data.tradeName;
        ideasDetail.value.time = +data.secondsName.replace('s', '');
        if (isCrm.value) {
            const params = {
                customerId: planDetail.value.customerId, // '5064257'
                joinTraderCode: userInfo.value.groupCode, //  'test-join-demo'
            };
            const { list } = await getCustomer(params) || [];
            if (!list.length) {
                ElMessage.error('未查询到签约单信息');
            }
            [customerDetail.value] = list.map((item) => ({
                ...item,
                industry: item.industryName,
                companyPropertyName: customerType[item.companyProperty],
            }));
        }
        await queryIdeas('');
    } finally {
        ideasLoading.value = false;
    }
    props.ideasId && handleGetIdeaInfo(props.ideasId);
    console.log('idealid:', props.ideasId);
};

const handleSreen = (materialDtoList) => {
    console.log('materialDtoList:', materialDtoList);
    curMediaType = planDetail.value.mediaType;
    screenModel.top.src =
        materialDtoList.find((item: any) => item.position === (curMediaType === 1 ? 1 : 4))?.showUrl || vidioNonSupport;
    screenModel.top.resourcesType = 2;
    const screen880 = materialDtoList.find((item: any) => item.position === (curMediaType === 1 ? 3 : 5))?.showUrl;
    const screen720 = materialDtoList.find((item: any) => item.position === (curMediaType === 1 ? 2 : 6))?.showUrl;
    screenModel.bottom.src = screen720 ? screen720 : screen880;

    screenModel.bottom.leftSrc = materialDtoList.find(
        (item: any) => item.position === (curMediaType === 1 ? 3 : 5)
    )?.showUrl;
    screenModel.bottom.rightSrc = materialDtoList.find(
        (item: any) => item.position === (curMediaType === 1 ? 2 : 6)
    )?.showUrl;

    console.log('===', curMediaType);
    if (curMediaType === 2) {
        screenModelSingle.top.src = materialDtoList.find((item: any) => item.position === 7).showUrl || vidioNonSupport;
        console.log('---', screenModelSingle.top.src);
        console.log('---', materialDtoList);
    }
};

watch(
    () => addForm.id,
    () => {
        handleGetIdeaInfo(addForm.id);
    }
);

onMounted(() => {
    handleGetPlanInfo();
});

const dialogVisible = ref(false);
const handleSubmit = async () => {
    if (!addForm.id) {
        ElMessage.error('请选择创意');
        return;
    }
    try {
        const params = {
            planId: planId.value,
            creativeId: addForm.id,
        };
        ideasLoading.value = true;
        const data = await confirmIdeas(params);
        ideasLoading.value = false;
        if (data.showMsg) {
            return true;
            // try {
            //     await ElMessageBox.confirm(data.msg, '提示', {
            //         confirmButtonText: '确认',
            //         cancelButtonText: '取消',
            //     });
            //     return true;
            // } catch (error) {
            //     console.log(error);
            // }
        }
        const msg = _.omit(data.checkPlanInfo, 'unitPrice');
        const dataList = Object.entries(msg).map(([type, data]) => ({
            type,
            ...data,
        }));
        tableList.value = dataList;
        dialogVisible.value = true;
    } catch (error) {
        ideasLoading.value = false;
    }
};

defineExpose({
    handleSubmit,
});
</script>

<style scoped lang="scss">
.out-screen {
    margin-right: 20px;
}

.el-form {
    .el-form-item {
        width: 45%;
        display: inline-flex;
        vertical-align: top;
        margin-bottom: 0 !important;

        &.block {
            display: flex;
            margin: 20px 0 12px 0 !important;

            :deep(.el-form-item__content) {
                line-height: 1.3;
            }
        }

        &.columns {
            :deep(.el-form-item__content) {
                flex-direction: column;
                align-items: flex-start;
            }
        }

        :deep(.el-form-item__label) {
            color: #999999;
        }

        :deep(.el-form-item__content) {
            line-height: 24px;
        }

        :deep(.el-date-editor),
        .el-input,
        .el-select,
        :deep(.el-cascader),
        .tips {
            width: 280px;

            & + .el-button {
                margin-left: 20px;
            }
        }

        .tips {
            line-height: 1.3;
            color: var(--el-text-color-placeholder);
        }

        .ideas {
            display: flex;
            flex: 1;
        }
    }
}
.mt-2 {
    margin-top: 20px;
}
.mb-2 {
    margin-bottom: 20px;
}
.red {
    color: red;
}
</style>
